const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerWebpackPlugin = require('css-minimizer-webpack-plugin');

module.exports = {
  optimization: {
    minimizer: [
      new CssMinimizerWebpackPlugin(),
    ],
    minimize: true,
  },
  entry: {
    index: './src/index.js',
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: './js/[name].js',
    clean: true,
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [MiniCssExtractPlugin.loader, 'css-loader'],
      },
      {
        test: /\.js$/i,
        exclude: /node_modules/,
        loader: 'eslint-loader',
      },
      {
        test: /\.(png|jpg|gif|svg|jpeg)$/i,
        type: 'asset/resource',
        generator: {
          filename: 'img/[name][hash:6][ext]',
        },
      },
      {
        test: /\.(png|jpg|gif|svg|jpeg)$/i,
        type: 'asset',
        parser: {
          dataUrlCondition: {
            // 图片文件大于16kb就原样输出，反之则转化为base64字符串
            maxSize: 16 * 1024,
          },
        },
      },
      {
        test: /\.(html|htm)$/i,
        loader: 'html-loader',
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html',
      filename: 'index.html',
      chunks: ['index'],
      minify: {
        minimize: true, // 是否打包为最小值
        // removeComments: true, // 去掉注释
        // collapseWhitespace: true, // 去掉空格
      },
    }),
    new MiniCssExtractPlugin({
      filename: './css/[name].css',
    }),
  ],
  mode: 'development',
  devServer: {
    static: './dist',
    port: 9000,
    client: {
      overlay: false,
    },
    hot: true,
  },
};
